<template>
    <div>
        <el-table :data="accountStore.allacountList" style="width: 100%" border="true">
            <el-table-column type="expand">
                <template #default="props">
                    <div m="4" class="detail">
                        <p m="t-0 b-2">总资产: {{ props.row }}</p>
                        {{ childtableData }}
                        <!-- <p m="t-0 b-2">可用余额: {{ props.row.available }}</p>
                        <p m="t-0 b-2">历史盈亏: {{ props.row.history.fee }}</p>
                        <p m="t-0 b-2">历史存取款: {{ props.row.history.dnw }}</p> -->
                        <h3>交易记录</h3>
                        <el-table :data="childtableData[index===props.row.id]"  :border="childBorder" height="400">
                            
                            <el-table-column label="交易编号" prop="order_id" />
                            <el-table-column label="交易时间" prop="create_time">
                                <template #default="scope">
                                    {{ convertToBeijingTime(scope.row.create_time) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="合约数量" prop="size" />
                            <el-table-column label="合约数量" prop="size">
                                <template #default="scope">
                                    <el-tag type="danger" v-if="scope.row.size>0">
                                        开多成功
                                    </el-tag>
                                    <el-tag type="success" v-else-if="scope.row.size<0">
                                        开空成功
                                    </el-tag>
                                    <el-tag type="info" v-else>
                                        平仓成功
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="开仓价格" prop="price" />
                            <el-table-column label="交易方式" prop="role">
                                <template #default="scope">
                                    <el-tag :type="scope.row.role === 'taker' ? 'success' : 'warning'">
                                        {{ scope.row.role === 'taker' ? '市价订单' : '限价订单' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="交易手续费" prop="fee" />

                        </el-table>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                v-for="column in tableColumns"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :sortable="column.sortable"
                :width="column.width"
            >
                <template v-if="column.prop=='total'" #default="scope">
                    <div>{{ scope.row[column.prop] }}</div>
                </template>
                <template v-if="column.customRender=='direction'" #default="scope">
                    <el-tag :type="scope.row[column.prop]>0?'success':'danger'">{{ scope.row[column.prop] }}</el-tag>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>
  
<script setup>
import { reactive, ref,onMounted } from 'vue';
import { useTeammemberdataStore } from '@/store/TableList.js'
import { getAccountPositions } from '@/api/apis'


// 账号信息
const accountStore = useTeammemberdataStore()

function getAccountPositionsfn(gate_key, gate_secret,id) {
    return new Promise((resolve, reject) => {
        getAccountPositions({
            gate_key,
            gate_secret,
            settle: 'usdt',
            holding: true,
            limit: 100,
            offset: 0
        }).then((res) => {
            const response = res.data;
            if (response.code === 200) {
                console.log(response.data);
                resolve({index:id,orderlist:response.data}); // 使用 resolve 返回正确的数据
            } else {
                console.error(`请求失败，错误代码：${response.code}，错误信息：${response.msg}`);
                reject(`请求失败：${response.msg}`); // 请求失败时 reject
            }
        }).catch((error) => {
            console.error('请求发生错误，请检查网络或稍后再试:', error);
            reject(error); // 网络或其他错误时 reject
        });
    });
}
// 获取用户账号信息
const childtableData = reactive([]);
function getAccounts(){
    const requests = accountStore.allacountList.map(account => 
        getAccountPositionsfn(account.gate_key, account.gate_secret,account.id)
    );

    Promise.all(requests)
    .then(results => {
        
        childtableData = results
        console.log('All data fetched:', results);

        // 在这里处理结果，比如存入数组等
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
}

// 使用 Promise.all 来并发执行所有请求
onMounted(async () => {

    await accountStore.getallacountList();
    getAccounts()
});


// 表格列配置
const tableColumns = ref([
    { label: '总资产', prop: 'total', sortable: true, customRender: 'total' },
    { label: '可用余额', prop: 'available', sortable: true },
    { label: '历史盈亏', prop: 'history.pnl', sortable: true },
    { label: '当前仓位数量', prop: 'size', sortable: true, customRender: 'size' },
    { label: '方向', prop: 'size', customRender: 'direction' },
    { label: '开仓价格', prop: 'in_dual_mode', sortable: true },
    { label: '标记价格', prop: 'enable_credit', sortable: true },
    { label: '历史手续费', prop: 'history.fee', sortable: true },
    { label: '持仓保证金', prop: 'position_margin', sortable: true },
    { label: '操作', prop: 'opreat',customRender: 'opreat',width:'180px' },
]);

// 表格数据
const tableData = ref([
    {
    total: '44.147976042514',
    unrealised_pnl: '-0.0745',
    position_margin: '1.50838725',
    order_margin: '0',
    available: '42.639588792514',
    point: '0',
    currency: 'USDT',
    in_dual_mode: false,
    enable_credit: false,
    position_initial_margin: '0',
    maintenance_margin: '0',
    bonus: '0',
    history: {
        dnw: '50',
        pnl: '0.25092',
        fee: '-6.1246627',
        refr: '0',
        fund: '0.021718742514',
        point_dnw: '0',
        point_fee: '0',
        point_refr: '0',
        bonus_dnw: '0',
        bonus_offset: '0'
    }
    },
    {
    total: '54.147976042514',
    unrealised_pnl: '-0.0745',
    position_margin: '1.50838725',
    order_margin: '0',
    available: '42.639588792514',
    point: '0',
    currency: 'USDT',
    in_dual_mode: false,
    enable_credit: false,
    position_initial_margin: '0',
    maintenance_margin: '0',
    bonus: '0',
    history: {
        dnw: '50',
        pnl: '0.25092',
        fee: '-6.1246627',
        refr: '0',
        fund: '0.021718742514',
        point_dnw: '0',
        point_fee: '0',
        point_refr: '0',
        bonus_dnw: '0',
        bonus_offset: '0'
    }
    }
]);



// 自定义渲染组件
const TotalCell =ref({
    template: `<div>{{ row[column.prop] }} - 总资产</div>`,
    props: ['row', 'column']
});

const UnrealisedPnlCell = {
    template: `<div>{{ row[column.prop] }} - 未实现盈亏</div>`,
    props: ['row', 'column']
};

// 动态添加自定义列内容
tableColumns.value.forEach(column => {
    if (column.prop === 'total') {
    column.customRender = TotalCell;
    } else if (column.prop === 'unrealised_pnl') {
    column.customRender = UnrealisedPnlCell;
    }
});

function convertToBeijingTime(timestamp) {
    // 将时间戳转换为毫秒
    const date = new Date(timestamp * 1000);

    // 获取中国东八区的时区偏移（以分钟为单位）
    const offset = date.getTimezoneOffset() * 60 * 1000; // 当前时区与UTC的时差，单位为毫秒
    const beijingOffset = -8 * 60 * 60 * 1000; // 北京时间与UTC的时差，单位为毫秒

    // 转换为北京时间
    const beijingTime = new Date(date.getTime() + offset + beijingOffset);

    return beijingTime.toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, '');
}





</script>
  
<style scoped>
/* 自定义样式 */
.total-cell {
    color: blue;
    font-weight: bold;
}

.unrealised-pnl-cell {
    color: red;
    font-style: italic;
}
.detail{
    p{
        margin-left: 30px;
    }
    h3{
        margin-left: 30px;
    }
}
</style>
  